﻿
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Xc.DataAccess.CodeReader.Models.Filters
{
    public class StructConverter
    {
        protected Dictionary<string, string> GetValues(string text)
        {
            Dictionary<string, string> keyValuePairs=new Dictionary<string, string>();
            var content=   text.Replace("(", string.Empty).Replace(")",string.Empty);
            var array=  content.Split(' ');
            foreach (var item in array)
            {
                var items=  item.Split(':');
                if (items==null)
                {
                    continue;
                }
                if (items.Length==2)
                {
                    keyValuePairs.Add(items[0].ToUpper(), items[1]);
                }
            }
            return keyValuePairs;
}
        private void SetValue<T>(T source, MemberInfo propertyInfo,object value)
        {

            if (propertyInfo is PropertyInfo info)
            {
                info.SetValue(source, ConvertValue(info.PropertyType,value));
            }
            else if (propertyInfo is FieldInfo infos)
            {
                infos.SetValue(source, ConvertValue(infos.FieldType, value));
            }
        }
        private object ConvertValue(Type type, object value)
        {
            if (type.IsEnum)
            {
                value = Enum.Parse(type, value?.ToString());
            }
            else if (type == typeof(Double))
            {
                value = double.Parse(value?.ToString());
            }
            else if (type == typeof(int))
            {
                value = int.Parse(value?.ToString());
            }
            return value;
        }
        protected T Map<T>(T text,Dictionary<string,string> keyValuePairs)
        {
            var ty = text.GetType().GetMembers();
            foreach (var item in ty)
            {
                if (keyValuePairs.ContainsKey(item.Name.ToUpper()))
                {
                    var value= keyValuePairs[item.Name.ToUpper()];
                    SetValue(text,item,value);  
                }
            }
            return text;
        }
    }

}
